﻿using System;


namespace homework03_4
{
    // 节点类
    public class Node<T>
    {
        public Node<T> Next { get; set; }
        public T Data { get; set; }

        public Node(T t)
        {
            Next = null;
            Data = t;
        }
    }

    // 泛型链表类
    public class GenericList<T>
    {
        private Node<T> head;
        private Node<T> tail;

        public GenericList()
        {
            tail = head = null;
        }

        public Node<T> Head
        {
            get => head;
        }

        public void Add(T t)
        {
            Node<T> n = new Node<T>(t);
            if (tail == null)
            {
                head = tail = n;
            }
            else
            {
                tail.Next = n;
                tail = n;
            }
        }

        // 添加 ForEach 方法
        public void ForEach(Action<T> action)
        {
            for (Node<T> node = head; node != null; node = node.Next)
            {
                action(node.Data);
            }
        }
    }

    class Program4
    {
        static void Main1(string[] args)
        {
            // 测试整数链表
            GenericList<int> intList = new GenericList<int>();
            for (int x = 0; x < 10; x++)
            {
                intList.Add(x);
            }

            // 1. 打印链表元素
            Console.WriteLine("链表元素：");
            intList.ForEach(x => Console.WriteLine(x));

            // 2. 求最大值
            int max = int.MinValue;
            intList.ForEach(x => max = Math.Max(max, x));
            Console.WriteLine($"最大值：{max}");

            // 3. 求最小值
            int min = int.MaxValue;
            intList.ForEach(x => min = Math.Min(min, x));
            Console.WriteLine($"最小值：{min}");

            // 4. 求和
            int sum = 0;
            intList.ForEach(x => sum += x);
            Console.WriteLine($"总和：{sum}");

            // 测试字符串链表
            GenericList<string> strList = new GenericList<string>();
            for (int x = 0; x < 10; x++)
            {
                strList.Add("str" + x);
            }

            // 打印字符串链表元素
            Console.WriteLine("\n字符串链表元素：");
            strList.ForEach(s => Console.WriteLine(s));
        }
    }
}
